package model

import (
	"context"
	"fmt"
	"time"
	"strings"
	"url_shorten/common/global"
	"url_shorten/internal/def"
	"url_shorten/internal/dto"
	"url_shorten/util"
)

func GetShortenUrl(url string) (string, error) {
	shortenCode := util.GenerateShortenUrl(6)
	err := global.REDIS.Set(context.TODO(), fmt.Sprintf(def.CacheUrl, shortenCode), url, def.ExpireTime24*time.Hour).Err()
	return shortenCode, err
}

func GetOriginUrl(shortenCode string) (string, error) {
	// fmt.Println(fmt.Sprintf(def.CacheUrl, shortenCode))
	url, err := global.REDIS.Get(context.TODO(), fmt.Sprintf(def.CacheUrl, shortenCode)).Result()
	return url, err
}

func GetStatsByShortenCode(shortenCode string) (int64, error) {
	count, err := global.REDIS.Get(context.TODO(), fmt.Sprintf(def.CacheStats, shortenCode)).Int64()
	return count, err
}

func GetStats() (res []*dto.ShortenStatisticsItem, err error) {
	var cursor uint64
	var keys []string
	for {
		var err error
		keys, cursor, err = global.REDIS.Scan(context.TODO(), cursor, fmt.Sprintf(def.CacheStats, "*"), 10).Result()
		// fmt.Println(keys, cursor, err) // got 10 keys, last cursor is 0, no more keys
		if err != nil {
			return nil, err
		}
		for _, key := range keys {
			count, err := global.REDIS.Get(context.TODO(), key).Int64()
			fmt.Println(count)
			if err != nil {
				return nil, err
			}
			shortenUrl := strings.Replace(key, fmt.Sprintf(def.CacheStats, ""), "", -1)
			item := &dto.ShortenStatisticsItem{
				ShortenUrl: shortenUrl,
				Statistics: count,	
			}
			res = append(res, item)
		}
		if cursor == 0 {
			break
		}
	}
	return res, nil
}

func IncrStatsByShortenCode(shortenCode string) (int64, error) {
	count, err := global.REDIS.Incr(context.TODO(), fmt.Sprintf(def.CacheStats, shortenCode)).Result()
	return count, err
}
